
package com.meixiaoliang.portal.core.util;

import java.math.BigInteger;
import java.security.MessageDigest;

/**
 * 加密工具类
 *
 * @author mei.xiaoliang@qq.com
 */
public class EncryptUtil {

    /**
     * 密码加密
     *
     * @param password  密码
     * @param salt      盐
     * @param transTime 转换次数
     * @return 加密后数据
     */
    public static String transform(String password, String salt, int transTime) {
        // 自创单向加密
        for (int i = 0; i < transTime; i++) {
            if (i % 3 == 0) {
                password = reverse(sha(password) + reverse(md5(salt)));
            } else {
                password = sha(password);
            }
        }
        password = sha(salt + password);
        return password;
    }

    private static String reverse(String str) {
        return new StringBuilder(str).reverse().toString();
    }

    /**
     * MD5 加密
     */
    private static String md5(String str) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(str.getBytes());
            return new BigInteger(1, md.digest()).toString(16);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * SHA 加密
     */
    private static String sha(String str) {
        try {
            MessageDigest md = MessageDigest.getInstance("SHA");
            md.update(str.getBytes());
            return new BigInteger(1, md.digest()).toString(16);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

}